package jschtest;

import com.jcraft.jsch.*;
import io.SshBean;
import org.apache.log4j.Logger;

import java.util.Map;
import java.util.Properties;

public class JschUtil {

    Session session = null;
    Channel channel = null;

    private static final Logger LOG = Logger.getLogger(JschUtil.class.getName());

    public static Session getSession(SshBean sshBean) throws JSchException{
        return getSession(sshBean.getUsername(), sshBean.getIp(),sshBean.getPort(), sshBean.getPassword());
    }

    public static Session getSession(String username, String ip, int port, String password) throws JSchException {
        JSch jSch = new JSch();
        Session session = jSch.getSession(username, ip, port);
        session.setPassword(password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config); // 为Session对象设置properties
        session.setTimeout(60000); // 设置timeout时间
        return session;
    }

    public ChannelSftp getSftpChannel(SshBean sshBean, int timeout) throws JSchException {
        return getSftpChannel(sshBean.getUsername(),sshBean.getPassword(),sshBean.getIp(),sshBean.getPort(),timeout);
    }

    public ChannelSftp getSftpChannel(String userName, String password,String hostIP,int port, int timeout) throws JSchException {
//        JSch jsch = new JSch(); // 创建JSch对象
//        session = jsch.getSession(userName, hosIP, port); // 根据用户名，主机ip，端口获取一个Session对象
        session = getSession(userName,hostIP, port,password);
        LOG.debug("Session created.");
        if (password != null) {
            session.setPassword(password); // 设置密码
        }
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config); // 为Session对象设置properties
        session.setTimeout(timeout); // 设置timeout时间
        session.connect(); // 通过Session建立链接
        LOG.debug("Session connected.");

        LOG.debug("Opening Channel.");
        channel = session.openChannel("sftp"); // 打开SFTP通道
        channel.connect(); // 建立SFTP通道的连接
        LOG.debug("Connected successfully to ftpHost = " + hostIP + ",as ftpUserName = " + userName
                + ", returning: " + channel);
        return (ChannelSftp) channel;
    }

    public void closeSftpChannel() {
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }
}
